
import sounddevice as sd
import numpy as np
from scipy.io.wavfile import write
from pydub import AudioSegment
from io import BytesIO
 
# 录制音频函数
def record_audio(duration, fs, channels):
    recording = sd.rec(int(duration * fs), samplerate=fs, channels=channels, dtype='int16')
    sd.wait()  # 等待录音完成
    return recording
 
# 参数设置
duration = 5  # 录音时长（秒）
fs = 44100  # 采样率
channels = 2  # 声道数
 
# 录制音频
recording = record_audio(duration, fs, channels)
 
# 将numpy数组保存为WAV文件（sounddevice默认录制为WAV）
with BytesIO() as output:
    write(output, fs, recording)
    output.seek(0)
    audio = AudioSegment.from_raw(output, format="wav", frame_rate=fs, channels=channels, sample_width=2)
    audio.export("output.flac", format="flac")  # 导出为FLAC格式